package com.example.yckjbigdataservice.utils;

import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.regionserver.KeyPrefixRegionSplitPolicy;
import org.apache.hadoop.conf.Configuration;

public class HBaseTableWithSplitPolicy {

    public static void main(String[] args) throws Exception {
        // 创建HBase配置
        Configuration config = HBaseConfiguration.create();
        config.set("hbase.zookeeper.quorum", "localhost");
        config.set("hbase.zookeeper.property.clientPort", "2181");

        // 创建连接和Admin对象
        try (Connection connection = ConnectionFactory.createConnection(config);
             Admin admin = connection.getAdmin()) {

            createTableWithKeyPrefixSplitPolicy(admin);
        }
    }

    /**
     * 创建带有KeyPrefixRegionSplitPolicy策略的表
     */
    public static void createTableWithKeyPrefixSplitPolicy(Admin admin) throws Exception {
        TableName tableName = TableName.valueOf("test_table");

        // 如果表已存在，先删除
        if (admin.tableExists(tableName)) {
            admin.disableTable(tableName);
            admin.deleteTable(tableName);
        }

        // 使用TableDescriptorBuilder创建表描述符
        TableDescriptorBuilder tableBuilder = TableDescriptorBuilder.newBuilder(tableName);

        // 设置Region分割策略为KeyPrefixRegionSplitPolicy
        tableBuilder.setRegionSplitPolicyClassName(KeyPrefixRegionSplitPolicy.class.getName());

        // 设置关键前缀长度（这是KeyPrefixRegionSplitPolicy的关键参数）
        // 例如：如果rowkey格式为 "prefix_timestamp"，前缀长度为6
        tableBuilder.setValue(KeyPrefixRegionSplitPolicy.PREFIX_LENGTH_KEY, "6");

        // 可选：设置其他表级别的配置
        tableBuilder.setMaxFileSize(10L * 1024 * 1024 * 1024); // 10GB
        tableBuilder.setMemStoreFlushSize(128L * 1024 * 1024); // 128MB

        // 创建列族
        ColumnFamilyDescriptorBuilder cfBuilder = ColumnFamilyDescriptorBuilder.newBuilder("cf1".getBytes());
        cfBuilder.setMaxVersions(3);
        cfBuilder.setTimeToLive(86400); // 1天TTL

        // 将列族添加到表描述符
        tableBuilder.setColumnFamily(cfBuilder.build());

        // 创建表
        TableDescriptor tableDescriptor = tableBuilder.build();
        admin.createTable(tableDescriptor);

        System.out.println("表创建成功：" + tableName.getNameAsString());
        System.out.println("分割策略：" + KeyPrefixRegionSplitPolicy.class.getName());
        System.out.println("前缀长度：6");
    }

    /**
     * 修改现有表的分割策略
     */
    public static void modifyTableSplitPolicy(Admin admin, String tableName) throws Exception {
        TableName table = TableName.valueOf(tableName);

        // 获取现有表描述符
        TableDescriptor oldDescriptor = admin.getDescriptor(table);

        // 创建新的表描述符构建器
        TableDescriptorBuilder newBuilder = TableDescriptorBuilder.newBuilder(oldDescriptor);

        // 修改分割策略
        newBuilder.setRegionSplitPolicyClassName(KeyPrefixRegionSplitPolicy.class.getName());
        newBuilder.setValue(KeyPrefixRegionSplitPolicy.PREFIX_LENGTH_KEY, "8");

        // 禁用表
        admin.disableTable(table);

        // 修改表
        admin.modifyTable(newBuilder.build());

        // 启用表
        admin.enableTable(table);

        System.out.println("表 " + tableName + " 的分割策略已修改");
    }

    /**
     * 创建带有预分割的表
     */
    public static void createTableWithPreSplit(Admin admin) throws Exception {
        TableName tableName = TableName.valueOf("pre_split_table");

        if (admin.tableExists(tableName)) {
            admin.disableTable(tableName);
            admin.deleteTable(tableName);
        }

        TableDescriptorBuilder tableBuilder = TableDescriptorBuilder.newBuilder(tableName);
        tableBuilder.setRegionSplitPolicyClassName(KeyPrefixRegionSplitPolicy.class.getName());
        tableBuilder.setValue(KeyPrefixRegionSplitPolicy.PREFIX_LENGTH_KEY, "4");

        // 创建列族
        ColumnFamilyDescriptorBuilder cfBuilder = ColumnFamilyDescriptorBuilder.newBuilder("data".getBytes());
        tableBuilder.setColumnFamily(cfBuilder.build());

        // 预分割键（基于前缀）
        byte[][] splitKeys = {
                "aaa\0".getBytes(),
                "bbb\0".getBytes(),
                "ccc\0".getBytes(),
                "ddd\0".getBytes()
        };

        // 创建带预分割的表
        admin.createTable(tableBuilder.build(), splitKeys);

        System.out.println("预分割表创建成功：" + tableName.getNameAsString());
    }

    /**
     * 验证表的分割策略配置
     */
    public static void verifyTableConfiguration(Admin admin, String tableName) throws Exception {
        TableName table = TableName.valueOf(tableName);
        TableDescriptor descriptor = admin.getDescriptor(table);

        String splitPolicy = descriptor.getRegionSplitPolicyClassName();
        String prefixLength = descriptor.getValue(KeyPrefixRegionSplitPolicy.PREFIX_LENGTH_KEY);

        System.out.println("表名: " + tableName);
        System.out.println("分割策略: " + splitPolicy);
        System.out.println("前缀长度: " + prefixLength);

        // 打印所有配置
        descriptor.getValues().forEach((key, value) -> {
            System.out.println(key + " = " + value);
        });
    }
}
